#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django import forms
from django.forms import widgets
from django.utils.safestring import mark_safe

from rbac import models
from rbac.forms.Base import BootStrapModelForm, BootStrapForm


class MenuModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        icon_obj = models.Icon.objects.all()
        ICON_LIST = []
        for i in icon_obj:
            cc = []
            cc.append(i.id)
            cc.append(mark_safe(i.tag))
            ICON_LIST.append(cc)

        self.fields['icon_id'].choices = ICON_LIST

    icon_id = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'clearfix'}), label='选择图标')

    class Meta:
        model = models.Menu
        fields = ['title', 'index', 'icon_id']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'index': forms.TextInput(attrs={'class': 'form-control'}),
            # 'icon_id': forms.RadioSelect(attrs={'class': 'form-control'},),
        }


class SecondMenuModelForm(BootStrapModelForm):
    class Meta:
        model = models.Permissions
        exclude = ['pid']


class PermissionModelForm(BootStrapModelForm):
    class Meta:
        model = models.Permissions
        fields = ['title', 'name', 'url']


class MultiAddPermissionForm(BootStrapForm):
    title = forms.CharField(widget=forms.TextInput())
    url = forms.CharField(widget=forms.TextInput())
    name = forms.CharField(widget=forms.TextInput())
    menu_id = forms.ChoiceField(
        choices=[(None, '-----')],
        widget=forms.Select(),
        required=False,
    )
    pid_id = forms.ChoiceField(
        choices=[(None, '-----')],
        widget=forms.Select(),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['menu_id'].choices += models.Menu.objects.values_list('id', 'title')
        self.fields['pid_id'].choices += models.Permissions.objects.filter(pid__isnull=True) \
            .exclude(menu__isnull=True).values_list('id', 'title')


class MultiEditPermissionForm(BootStrapForm):
    id = forms.IntegerField(widget=forms.HiddenInput())
    title = forms.CharField(widget=forms.TextInput())
    url = forms.CharField(widget=forms.TextInput())
    name = forms.CharField(widget=forms.TextInput())
    menu_id = forms.ChoiceField(
        choices=[(None, '-----')],
        widget=forms.Select(),
        required=False,
    )
    pid_id = forms.ChoiceField(
        choices=[(None, '-----')],
        widget=forms.Select(),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['menu_id'].choices += models.Menu.objects.values_list('id', 'title')
        self.fields['pid_id'].choices += models.Permissions.objects.filter(pid__isnull=True) \
            .exclude(menu__isnull=True).values_list('id', 'title')
